package com.dkm.orproject.dkmoa.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dkm.orproject.dkmoa.domain.OaDepartment;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.domain.vo.OaDepartmentVo;
import com.dkm.orproject.dkmoa.service.OaDepartmentService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.IdToobtainUtils;
import com.dkm.orproject.utils.utils.Tools;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  @ClassName : OaDepartmentAction  //类名
 *  @Description : 部门  //描述
 *  @Author : 石智诚  //作者
 *  @Date: 2020-08-05 11:27  //时间
 */
@RestController
@RequestMapping("OaDepartmentAction")
public class OaDepartmentAction {
    /**
     * 部门接口
     */
    @Resource
    OaDepartmentService departmentService;

    @Resource
    IdToobtainUtils utils;
    /**
     * 工具类
     */
    @Resource
    Tools tools;
    /**
     * 日志
     */
    OaLog log;
    /**
     * 登陆人
     */
    OaPersonnel person;

    /**
     * 回调map
     */
    Map<String,Object> map;
    /**
     * 行数
     */
    int row;

    /**
     * 查询部门(下拉框)
     * @return id 和部门名
     */
    @GetMapping("departmentfindByAll")
    @UserLoginToken
    public Map<String,Object> findByAll(HttpServletRequest request){
        rowMap(request);
        try{
            List<OaDepartment> all = departmentService.findByAll();
            return Tools.maps(all, null);
        }catch (Exception e){
            addErrorLog(request,"公司查询",e);
        }
        return null;
         }
    /**
     * 更新和增加部门信息的
     * @param department 更改人员以后的信息
     * @param request 请求
     * @return 成功与否
     */
    @PostMapping("addOrUpdateDepartment")
    @UserLoginToken
    public Map<String, Object> addOrUpdateDepartment (@RequestBody OaDepartment department, HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(department)){
            tools.rowMap(map,0,null);
        }
        try {
            if (department.getPkDepartmentId()!=null &&department.getPkDepartmentId()>0){
                department.setUpdatedBy(person.getPersonnelName());
                row= departmentService.update(department);
                log.setLogTitle("公司更新");
            }else {
                department.setIsRevision("1");
                //公司id 随机生成
                department.setPkDepartmentId(utils.getNumberId());
                department.setCreatedBy(person.getPersonnelName());
                row=departmentService.insert(department);
                log.setLogTitle("公司增加");
            }
            log.setLogBody(JSON.toJSON(row).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"公司增加或者更新模块",e);
        }
        return map;
    }

    /**
     * 根据id查询的部门信息(编辑用的)
     *
     * @param pkDepartmentId 部门id
     * @param request 请求
     * @return 是否更新成功
     */
    @GetMapping("selectById/{pkDepartmentId}")
    @UserLoginToken
    public Map<String, Object> selectById(@PathVariable("pkDepartmentId") Long pkDepartmentId, HttpServletRequest request) {
       rowMap(request);
        try {
            OaDepartment department = departmentService.selectByDepartmentId(pkDepartmentId);
            map.put("data",department);
        } catch (Exception e) {
            addErrorLog(request,"根据id查询的部门信息模块",e);
        }
        return map;
    }
    /**
     * 根据id查询的信息(查看)
     *
     * @param pkDepartmentId 部门id
     * @param request 请求
     * @return 是否更新成功
     */
    @GetMapping("findById/{pkDepartmentId}")
    @UserLoginToken
    public Map<String, Object> findById(@PathVariable("pkDepartmentId") Long pkDepartmentId, HttpServletRequest request) {
        rowMap(request);
        try {
            OaDepartmentVo departmentVo = departmentService.selectById(pkDepartmentId);
            map.put("data",departmentVo);
        } catch (Exception e) {
            addErrorLog(request,"根据id查询的部门信息模块",e);
        }
        return map;
    }

    /**
     * 逻辑删除
     *
     * @param pkDepartmentId 部门ID
     * @param request       操作的
     * @return 操作的结果
     */
    @PutMapping("updateById/{pkDepartmentId}")
    @UserLoginToken
    public Map<String, Object> updateById(@PathVariable("pkDepartmentId") Long pkDepartmentId, HttpServletRequest request) {
        rowMap(request);
        try {
            row = departmentService.updateById(pkDepartmentId,person.getPersonnelName());
            log.setLogTitle("删除模块");
            log.setLogBody(JSON.toJSON(row).toString());
            log.setLogType("1");
            tools.rowMap(map, row, log);
        } catch (Exception e) {
            addErrorLog(request,"部门逻辑删除模块",e);
        }
        return map;
    }

    /**
     * 删除
     *
     * @param pkDepartmentId 用户ID
     * @param request       操作的
     * @return 结果
     */
    @UserLoginToken
    @DeleteMapping("deleteDepartment/{pkDepartmentId}")
    public Map<String, Object> delete(@PathVariable("pkDepartmentId") Long pkDepartmentId, HttpServletRequest request) {
      rowMap(request);
        try {
            int  delete= departmentService.delete(pkDepartmentId);
            log.setLogTitle("部门物理删除模块");
            log.setLogBody(JSON.toJSON(delete).toString());
            log.setLogType("1");
            tools.rowMap(map, delete, log);
        } catch (Exception e) {
            addErrorLog(request,"部门物理删除",e);
        }
        return map;
    }

    /**
     * 查询分页
     *
     * @param department 部门信息
     * @param page      第几页
     * @param limit     返回的数据条数
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param request 请求
     * @return 分页的数据和总数
     */
    @UserLoginToken
    @GetMapping("findAll")
    public Map<String, Object> findAll(OaDepartment department, int page, int limit, String startTime, String endTime, HttpServletRequest request) {
        try {
            List<OaDepartment> all = departmentService.findAll(department, page, limit, startTime, endTime);
            Long count = departmentService.rowCount(department, startTime, endTime);
           return Tools.maps(all, count);
        } catch (Exception e) {
            addErrorLog(request,"部门查询模块",e);
        }
        return  null;
    }

    /**
     * 批量删除
     * @param ids 人员id的集合
     * @param request 请求
     * @return 删除的行数
     */
    @PostMapping("updateAll")
    @UserLoginToken
    public Map<String, Object> updateAll(@RequestParam(value = "ids[]",required = false) Long[] ids, HttpServletRequest request) {
        rowMap(request);
        List<Long> idssi;
        if(ObjectUtils.isEmpty(ids)){
            return tools.rowMap(map,0,null);
        }else{
            idssi= Arrays.asList(ids);
        }

        try {
            int updateAll = departmentService.updateAll(idssi,person.getPersonnelName());
            log.setLogTitle("逻辑删除模块");
            log.setLogBody(JSON.toJSON(idssi).toString());
            log.setLogType("1");
            tools.rowMap(map, updateAll, log);
        } catch (Exception e) {
            addErrorLog(request,"逻辑删除模块",e);
        }
        return map;
    }

    /**
     * 批量删除
     * @param ids 部门id的集合
     * @param session 操作人的session
     * @param request 请求
     * @return 是否删除的
     */
    @DeleteMapping("deleteAll")
    @UserLoginToken
   public Map<String, Object> deleteAll(@RequestParam(value = "ids[]", required = false) Long[] ids, HttpSession session, HttpServletRequest request) {
       rowMap(request);

        List<Long> idss;
        if (ObjectUtils.isEmpty(ids)){
            return tools.rowMap(map,0,null);
        }else {
            idss= Arrays.asList(ids);
        }

        try {
            int deleteAll = departmentService.deleteAll(idss);
            log.setLogTitle("删除模块");
            log.setLogBody(JSON.toJSON(deleteAll).toString());
            log.setLogType("1");
            tools.rowMap(map, deleteAll, log);
            map.put("data",deleteAll);
        } catch (Exception e) {
            addErrorLog(request,"部门删除模块",e);
        }
        return map;
    }

    /**
     * 简化代码
     * @param request 请求
     */
    private void rowMap(HttpServletRequest request){
        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        person= (OaPersonnel) request.getSession().getAttribute("user");
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(person.getPersonnelName());
    }

    private void addErrorLog(HttpServletRequest request,String title,Exception e){
        OaPersonnel personnel= (OaPersonnel) request.getSession().getAttribute("user");
        log=new OaLog();
        log.setLogType("0");
        log.setLogBody(JSONObject.toJSON(e.getStackTrace()).toString());
        log.setLogTitle(title);
        log.setLogIp(request.getRemoteAddr());
        if(ObjectUtils.isEmpty(personnel)){
            log.setCreatedBy(person.getPersonnelName());
        }
        tools.errorMap(log);
    }
}
